package com.liuyk.util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.widget.ImageView;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * 参考图库算法，压缩Bitmap 解决OOM
 *
 * @author liuyk
 */
public class CropImage {

	public static Bitmap decodeBitmap(String path, int width, int height) {
		final Options options = new Options();
        //设置Options
		options.inJustDecodeBounds = true;//只取大小，不占用内存
		options.inSampleSize = computeSampleSize(options, width, height);
		options.inJustDecodeBounds = false;//这里一定要将其设置回false，因为之前我们将其设置成了true
		options.inDither = false;
		options.inTempStorage = new byte[16 * 1024];
		
		Bitmap bitmap;
		try {
			final FileInputStream inputStream = new FileInputStream(path);
			final Bitmap bitmap1 = BitmapFactory.decodeFileDescriptor(inputStream.getFD(), null, options);
			double scale = getScaling(options.outWidth * options.outHeight,  
                    1024 * 600);
			bitmap = Bitmap.createScaledBitmap(bitmap1, 
					(int)(options.outWidth*scale), (int)(options.outHeight*scale), true);

			bitmap1.recycle();
			inputStream.close();
		} catch (Exception e) {
			bitmap = null;
		} 
		
		return bitmap;
	}
   
    private static double getScaling(int src, int des) {  
        /** 
         * 48 目标尺寸÷原尺寸 sqrt开方，得出宽高百分比 49
         */ 
        double scale = Math.sqrt((double) des / (double) src);  
        return scale;  
    }  
   
    public static int computeSampleSize(Options options,
            int minSideLength, int maxNumOfPixels) {  
        int initialSize = computeInitialSampleSize(options, minSideLength,  
                maxNumOfPixels);  
   
        int roundedSize;  
        if (initialSize <= 8) {  
            roundedSize = 1;  
            while (roundedSize < initialSize) {  
                roundedSize <<= 1;  
            }  
        } else {  
            roundedSize = (initialSize + 7) / 8 * 8;  
        }  
   
        return roundedSize;  
    }  
   
    private static int computeInitialSampleSize(Options options,
            int minSideLength, int maxNumOfPixels) {  
        double w = options.outWidth;  
        double h = options.outHeight;  
   
        int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math  
                .sqrt(w * h / maxNumOfPixels));  
        int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(  
                Math.floor(w / minSideLength), Math.floor(h / minSideLength));  
   
        if (upperBound < lowerBound) {  
            return lowerBound;  
        }  
   
        if ((maxNumOfPixels == -1) && (minSideLength == -1)) {  
            return 1;  
        } else if (minSideLength == -1) {  
            return lowerBound;  
        } else {  
            return upperBound;  
        }  
    }

    @SuppressWarnings("null")
    @Deprecated
    public static byte[] decodeBitmap(String path , ImageView iv) {
        final Options opts = new Options();
        opts.inJustDecodeBounds = true;//设置成了true,不占用内存，只获取bitmap宽高
        BitmapFactory.decodeFile(path, opts);//1024 * 800
        opts.inSampleSize = computeSampleSize(opts, -1, iv.getHeight()*iv.getWidth());
        opts.inJustDecodeBounds = false;//这里一定要将其设置回false，因为之前我们将其设置成了true
        opts.inDither = false;
        opts.inTempStorage = new byte[16 * 1024];
        FileInputStream in = null;
        Bitmap bmp;
        ByteArrayOutputStream baos = null;
        try {
            in = new FileInputStream(path);
            bmp = BitmapFactory.decodeFileDescriptor(in.getFD(), null, opts);
            double scale = getScaling(opts.outWidth * opts.outHeight,
                    1024 * 600);
            Bitmap bmp2 = Bitmap.createScaledBitmap(bmp,
                    (int) (opts.outWidth * scale),
                    (int) (opts.outHeight * scale), true);
            bmp.recycle();
            baos = new ByteArrayOutputStream();
            bmp2.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            bmp2.recycle();
            return baos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
                baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.gc();
        }
        return baos.toByteArray();
    }
}
